package com.aids_malaria.ui;

import android.view.KeyEvent;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;

import com.aids_malaria.R;
import com.aids_malaria.app.Constant;
import com.aids_malaria.base.BaseActivity;
import com.aids_malaria.db.DBManager;
import com.aids_malaria.event.Events;
import com.aids_malaria.http.RetrofitFactory;
import com.aids_malaria.http.RxScheduler;
import com.aids_malaria.http.api.RetrofitApi;
import com.aids_malaria.http.response.DoLoginResponse;
import com.aids_malaria.http.response.login.LoginObserver;
import com.aids_malaria.http.response.register.RegistObserver;
import com.aids_malaria.util.AppUtil;
import com.aids_malaria.util.SpUtil;
import com.aids_malaria.util.StringUtil;
import com.aids_malaria.util.ToastUtil;
import com.luck.picture.lib.rxbus2.Subscribe;

import butterknife.BindView;
import butterknife.OnClick;

public class LoginActivity extends BaseActivity {

    @BindView(R.id.et_username)
    EditText etUsername;
    @BindView(R.id.et_password)
    EditText etPassword;
    @BindView(R.id.cb_rem_pwd)
    CheckBox cbRemPwd;
    @BindView(R.id.tv_regist)
    TextView tv_regist;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_login;
    }

    @Override
    protected void initView() {
        super.initView();
        boolean isRememberAccount = SpUtil.getBoolean(mContext, Constant.IS_REMEMBER_ACCOUNT, false);
        if (isRememberAccount) {
            String userName = SpUtil.getString(mContext, Constant.USER_ACCOUNT, "");
            etUsername.setText(userName);
        }
    }

    @Override
    protected void initData() {
        super.initData();
    }

    @OnClick({R.id.tv_login,R.id.tv_regist})
    public void onClick(View view) {
        String userName = etUsername.getText().toString().trim();
        String password = etPassword.getText().toString().trim();

        String deviceId = AppUtil.getDeviceId(mContext);
        if (StringUtil.isEmpty(userName) || StringUtil.isEmpty(password)) {
            ToastUtil.showToast(getString(R.string.login_null));
            return;
        }
        switch (view.getId()) {
            case R.id.tv_login:
                doLogin(userName, deviceId, password);
                break;
            case R.id.tv_regist:
                doRegister(userName, deviceId, password);
                break;
                default:
                    break;
        }
    }

    /**
     * 登录
     *
     * @param userCode
     * @param padId
     * @param password
     */
    private void doLogin(String userCode, String padId, String password) {
        getLoadingDialog().show();
        RetrofitFactory.getInstance().createApi(RetrofitApi.class).dologin(userCode, padId, password)
                .compose(RxScheduler.rxSchedulerTransform())
                .subscribe(new LoginObserver<DoLoginResponse>(){

                    @Override
                    protected void onStart() {
                        getLoadingDialog().show();
                    }

                    @Override
                    protected void onSuccess(DoLoginResponse data) throws Exception {
                        //保存是否记住账号
                        SpUtil.putBoolean(mContext, Constant.IS_REMEMBER_ACCOUNT, cbRemPwd.isChecked());
                        //保存登录状态
                        SpUtil.putBoolean(mContext, Constant.IS_LOGIN, true);
                        //保存登录信息
                        SpUtil.putString(mContext, Constant.TOKEN, data.getToken());
                        SpUtil.putString(mContext, Constant.USER_ACCOUNT, data.getUser_code());
                        SpUtil.putString(mContext, Constant.USER_ACCOUNT_NAME, data.getUser_name());
                        SpUtil.putString(mContext, Constant.USER_PASSWORD, password);
                        SpUtil.putString(mContext, Constant.PAD_SEQ, data.getPADSEQ());

                        //保存权限在本地
                        DBManager.get().loginUserAuthDao().deleteAll();
                        DBManager.get().loginUserAuthDao().insertAll(data.getAUTH());

                        startActivity(MainActivity.class);
                        finish();
                    }

                    @Override
                    protected void onFinish() {
                        getLoadingDialog().dismiss();
                    }

                });
    }

    /**
     * 注册
     *
     * @param userCode
     * @param padId
     * @param password
     */
    private void doRegister(String userCode, String padId, String password) {
        RetrofitFactory.getInstance().createApi(RetrofitApi.class).doRegister(userCode, padId, password)
                .compose(RxScheduler.rxSchedulerTransform())
                .subscribe(new RegistObserver<Object>() {
                    @Override
                    protected void onStart() {
                        getLoadingDialog().show();
                    }

                    @Override
                    protected void onSuccess(Object data) throws Exception {

                    }

                    @Override
                    protected void onFinish() {
                        getLoadingDialog().dismiss();
                    }
                });
    }

    private long exitTime = 0;
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            //两秒之内按返回键就会退出
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                ToastUtil.showToast(getString(R.string.exist_app));
                exitTime = System.currentTimeMillis();
            } else {
                finish();
                System.exit(0);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
    /**
     * 连接失败事件回调，隐藏loading框
     * @param
     */
    @Subscribe
    public void onCodeEvent(Events.resistPadError type){
        tv_regist.setVisibility(View.VISIBLE);
    }

    @Subscribe
    public void onCodeEvent(Events.registSuccess linkEvent) {
        tv_regist.setVisibility(View.GONE);
    }
}
